package com.dev.security.config.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.util.PatternMatchUtils;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.support.RequestContext;

import com.dev.security.login.service.LoginManager;
import com.dev.security.login.util.LoginConstants;

/**
 * @author 潜行的青衣
 * @see
 */
@WebFilter(
	filterName="securityFilter", 
	servletNames = {"dispatcher"}
)
public class SecurityFilter implements Filter {

	private static final Logger LOG = LogManager.getLogger(SecurityFilter.class);
	
	private LoginManager loginManager;
	
	/* (non-Javadoc)
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		if(loginManager == null) {
			synchronized(this) {
				if(loginManager == null) {
					loginManager = WebApplicationContextUtils
						.getWebApplicationContext(request.getServletContext()).getBean(LoginManager.class);
				}
			}
		}
		String ctx = req.getContextPath();
		String uri = req.getRequestURI().substring(ctx.length());
		if(!PatternMatchUtils.simpleMatch("/resources/**", uri) ||
				PatternMatchUtils.simpleMatch("/resources/apps/*.js", uri)) {
			LOG.info("------校验：{}", uri);
			int code = this.loginManager.validate(req, resp, uri);
			boolean isTransit = LoginConstants.VALIDATE_TRANSIT == code;
			if(!isTransit) {
				LOG.warn("-----访问失败，校验代码：{}", code);
				RequestContext requestContext = new RequestContext(req, req.getServletContext());
				if(code == LoginConstants.VALIDATE_NOLOGIN) {
					resp.setStatus(HttpStatus.NON_AUTHORITATIVE_INFORMATION.value());
					req.setAttribute("error_message", requestContext.getMessage("login.error.timeout"));
				} else {
					resp.setStatus(HttpStatus.FORBIDDEN.value());
					req.setAttribute("error_message", requestContext.getMessage("login.error.forbidden"));
				}
				req.getRequestDispatcher("/login/page").forward(request, response);
				return;
			}
		}
		chain.doFilter(request, response);
	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#destroy()
	 */
	@Override
	public void destroy() {
	}

}
